package org.testframe;

import com.csvreader.CsvReader;

import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * csv 数据源
 * @author 丁常磊
 * @date 2023/11/21 11:34
 */

public class CsvDataSource implements DataSource {

    private final CsvReader csvReader;

    private  List<List<String>> allLines;

    private int currentLine = 0;

    public CsvDataSource(String path, char splitChar, Charset charset) throws FileNotFoundException {
        csvReader = new CsvReader(path, splitChar, charset);
    }

    @Override
    public void skip(int line) {
        for (int i = 0; i < line; i++) {
            try {
                csvReader.readRecord();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public List<String> readLine(ReadMode readMode) {
        try {
            if (allLines == null) {
                allLines = new ArrayList<>();
                while (csvReader.readRecord()) {
                    String[] values = csvReader.getValues();
                    allLines.add(Arrays.asList(values));
                }
            }

            if (allLines.size() == 0) {
                return null;
            }

            if (readMode == ReadMode.random) {
                return allLines.get(new Random().nextInt(allLines.size()));
            } else if (readMode == ReadMode.circulation) {
                List<String> list = allLines.get(currentLine);
                currentLine++;
                if (currentLine >= allLines.size()) {
                    currentLine = 0;
                }
                return list;
            } else {
                throw new IllegalArgumentException("不支持的模式:" + readMode);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void close() throws IOException {
        csvReader.close();
    }
}
